<template>
  <div class="points-record">
    <div class="page-header">
      <h2>积分记录与登记</h2>
      <div class="header-actions">
        <el-button type="primary" @click="showCreateDialog">
          <el-icon><Plus /></el-icon>
          新增记录
        </el-button>
        <el-button @click="showBatchImportDialog">
          <el-icon><Upload /></el-icon>
          批量导入
        </el-button>
        <el-button @click="downloadTemplate">
          <el-icon><Download /></el-icon>
          下载模板
        </el-button>
      </div>
    </div>

    <!-- 搜索筛选 -->
    <div class="search-form">
      <el-form :model="searchForm" inline>
        <el-form-item label="部门">
          <el-select v-model="searchForm.departmentId" placeholder="请选择部门" clearable>
            <el-option
              v-for="dept in departments"
              :key="dept.id"
              :label="dept.name"
              :value="dept.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="积分类型">
          <el-select v-model="searchForm.pointsType" placeholder="请选择类型" clearable>
            <el-option label="加分" value="add" />
            <el-option label="扣分" value="deduct" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="待审批" value="pending" />
            <el-option label="已通过" value="approved" />
            <el-option label="已拒绝" value="rejected" />
            <el-option label="已取消" value="cancelled" />
          </el-select>
        </el-form-item>
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="关键词">
          <el-input
            v-model="searchForm.keyword"
            placeholder="请输入事件描述或责任人"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 数据表格 -->
    <div class="table-container">
      <el-table
        v-loading="loading"
        :data="tableData"
        stripe
        border
        style="width: 100%"
      >
        <el-table-column prop="recordTime" label="记录时间" width="160" />
        <el-table-column prop="departmentName" label="部门" width="120" />
        <el-table-column prop="responsiblePersonName" label="责任人" width="100" />
        <el-table-column prop="eventDescription" label="事件描述" min-width="200" show-overflow-tooltip />
        <el-table-column prop="pointsType" label="积分类型" width="100">
          <template #default="{ row }">
            <el-tag :type="row.pointsType === 'add' ? 'success' : 'danger'">
              {{ row.pointsType === 'add' ? '加分' : '扣分' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="pointsValue" label="积分分值" width="100">
          <template #default="{ row }">
            <span :class="row.pointsType === 'add' ? 'text-success' : 'text-danger'">
              {{ row.pointsType === 'add' ? '+' : '-' }}{{ row.pointsValue }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="recorderName" label="记录人" width="100" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="viewDetail(row)">
              查看
            </el-button>
            <el-button
              v-if="row.status === 'pending'"
              type="warning"
              size="small"
              @click="editRecord(row)"
            >
              编辑
            </el-button>
            <el-button
              v-if="row.status === 'pending'"
              type="danger"
              size="small"
              @click="deleteRecord(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="createDialogVisible"
      :title="isEdit ? '编辑积分记录' : '新增积分记录'"
      width="800px"
      @close="resetForm"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="formRules"
        label-width="120px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="部门" prop="departmentId">
              <el-select v-model="form.departmentId" placeholder="请选择部门" @change="handleDepartmentChange">
                <el-option
                  v-for="dept in departments"
                  :key="dept.id"
                  :label="dept.name"
                  :value="dept.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="责任人" prop="responsiblePersonId">
              <el-select v-model="form.responsiblePersonId" placeholder="请选择责任人">
                <el-option
                  v-for="user in departmentUsers"
                  :key="user.id"
                  :label="user.name"
                  :value="user.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="事件描述" prop="eventDescription">
          <el-input
            v-model="form.eventDescription"
            type="textarea"
            :rows="3"
            placeholder="请详细描述积分事件"
          />
        </el-form-item>
        
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="积分类型" prop="pointsType">
              <el-radio-group v-model="form.pointsType">
                <el-radio value="add">加分</el-radio>
                <el-radio value="deduct">扣分</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="积分分值" prop="pointsValue">
              <el-input-number
                v-model="form.pointsValue"
                :min="1"
                :max="100"
                placeholder="请输入分值"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="严重程度" prop="severity">
              <el-select v-model="form.severity" placeholder="请选择严重程度">
                <el-option label="低" value="low" />
                <el-option label="中" value="medium" />
                <el-option label="高" value="high" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="地点" prop="location">
          <el-input v-model="form.location" placeholder="请输入事件发生地点" />
        </el-form-item>
        
        <el-form-item label="附件">
          <el-upload
            v-model:file-list="form.attachments"
            action="/api/upload"
            list-type="picture-card"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :before-upload="beforeUpload"
            multiple
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="createDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          {{ isEdit ? '更新' : '创建' }}
        </el-button>
      </template>
    </el-dialog>

    <!-- 批量导入对话框 -->
    <el-dialog
      v-model="batchImportDialogVisible"
      title="批量导入积分记录"
      width="600px"
    >
      <el-form :model="importForm" label-width="120px">
        <el-form-item label="选择文件">
          <el-upload
            ref="uploadRef"
            :auto-upload="false"
            :on-change="handleFileChange"
            :before-upload="beforeUpload"
            accept=".xlsx,.xls"
            drag
          >
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">
              将文件拖到此处，或<em>点击上传</em>
            </div>
            <template #tip>
              <div class="el-upload__tip">
                只能上传 xlsx/xls 文件，且不超过 10MB
              </div>
            </template>
          </el-upload>
        </el-form-item>
        
        <el-form-item label="默认部门">
          <el-select v-model="importForm.departmentId" placeholder="请选择默认部门（可选）">
            <el-option
              v-for="dept in departments"
              :key="dept.id"
              :label="dept.name"
              :value="dept.id"
            />
          </el-select>
        </el-form-item>
        
      </el-form>
      
      <template #footer>
        <el-button @click="batchImportDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleBatchImport" :loading="importing">
          开始导入
        </el-button>
      </template>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="积分记录详情"
      width="800px"
    >
      <div v-if="currentRecord" class="record-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="记录时间">
            {{ currentRecord.recordTime }}
          </el-descriptions-item>
          <el-descriptions-item label="部门">
            {{ currentRecord.departmentName }}
          </el-descriptions-item>
          <el-descriptions-item label="责任人">
            {{ currentRecord.responsiblePersonName }}
          </el-descriptions-item>
          <el-descriptions-item label="记录人">
            {{ currentRecord.recorderName }}
          </el-descriptions-item>
          <el-descriptions-item label="积分类型">
            <el-tag :type="currentRecord.pointsType === 'add' ? 'success' : 'danger'">
              {{ currentRecord.pointsType === 'add' ? '加分' : '扣分' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="积分分值">
            <span :class="currentRecord.pointsType === 'add' ? 'text-success' : 'text-danger'">
              {{ currentRecord.pointsType === 'add' ? '+' : '-' }}{{ currentRecord.pointsValue }}
            </span>
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusType(currentRecord.status)">
              {{ getStatusText(currentRecord.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="地点">
            {{ currentRecord.location || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="严重程度">
            <el-tag :type="getSeverityType(currentRecord.severity)">
              {{ getSeverityText(currentRecord.severity) }}
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>
        
        <div class="event-description">
          <h4>事件描述</h4>
          <p>{{ currentRecord.eventDescription }}</p>
        </div>
        
        <div v-if="currentRecord.attachments && currentRecord.attachments.length" class="attachments">
          <h4>附件</h4>
          <div class="attachment-list">
            <div
              v-for="(attachment, index) in currentRecord.attachments"
              :key="index"
              class="attachment-item"
            >
              <el-image
                v-if="isImage(attachment)"
                :src="attachment"
                :preview-src-list="currentRecord.attachments"
                style="width: 100px; height: 100px"
                fit="cover"
              />
              <div v-else class="file-item">
                <el-icon><Document /></el-icon>
                <span>{{ getFileName(attachment) }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Upload, Download, Search, Refresh, Document } from '@element-plus/icons-vue'
import { pointsRecordApi } from '@/api/points'
import type { PointsRecord, CreatePointsRecordParams } from '@/types/points'

// 响应式数据
const loading = ref(false)
const submitting = ref(false)
const importing = ref(false)
const tableData = ref<PointsRecord[]>([])
const departments = ref([])
const departmentUsers = ref([])
const currentRecord = ref<PointsRecord | null>(null)

// 对话框状态
const createDialogVisible = ref(false)
const batchImportDialogVisible = ref(false)
const detailDialogVisible = ref(false)
const isEdit = ref(false)

// 搜索表单
const searchForm = reactive({
  departmentId: '',
  pointsType: '',
  status: '',
  dateRange: [],
  keyword: ''
})

// 分页
const pagination = reactive({
  page: 1,
  pageSize: 20,
  total: 0
})

// 表单数据
const form = reactive<CreatePointsRecordParams & { id?: string }>({
  departmentId: '',
  responsiblePersonId: '',
  eventDescription: '',
  pointsType: 'add',
  pointsValue: 1,
  attachments: [],
  location: '',
  severity: 'low'
})

// 导入表单
const importForm = reactive({
  file: null as File | null,
  departmentId: ''
})

// 表单验证规则
const formRules = {
  departmentId: [{ required: true, message: '请选择部门', trigger: 'change' }],
  responsiblePersonId: [{ required: true, message: '请选择责任人', trigger: 'change' }],
  eventDescription: [{ required: true, message: '请输入事件描述', trigger: 'blur' }],
  pointsType: [{ required: true, message: '请选择积分类型', trigger: 'change' }],
  pointsValue: [{ required: true, message: '请输入积分分值', trigger: 'blur' }]
}

// 计算属性
const formRef = ref()
const uploadRef = ref()

// 方法
const loadData = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.page,
      pageSize: pagination.pageSize,
      ...searchForm,
      startTime: searchForm.dateRange?.[0],
      endTime: searchForm.dateRange?.[1]
    }
    
    const response = await pointsRecordApi.getList(params)
    tableData.value = response.list
    pagination.total = response.total
  } catch (error) {
    ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.page = 1
  loadData()
}

const handleReset = () => {
  Object.assign(searchForm, {
    departmentId: '',
    pointsType: '',
    status: '',
    dateRange: [],
    keyword: ''
  })
  handleSearch()
}

const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  pagination.page = 1
  loadData()
}

const handleCurrentChange = (page: number) => {
  pagination.page = page
  loadData()
}

const showCreateDialog = () => {
  isEdit.value = false
  createDialogVisible.value = true
  resetForm()
}

const editRecord = (row: PointsRecord) => {
  isEdit.value = true
  createDialogVisible.value = true
  Object.assign(form, {
    id: row.id,
    departmentId: row.departmentId,
    responsiblePersonId: row.responsiblePersonId,
    eventDescription: row.eventDescription,
    pointsType: row.pointsType,
    pointsValue: row.pointsValue,
    attachments: row.attachments,
    location: row.location,
    severity: row.severity
  })
}

const viewDetail = (row: PointsRecord) => {
  currentRecord.value = row
  detailDialogVisible.value = true
}

const deleteRecord = async (row: PointsRecord) => {
  try {
    await ElMessageBox.confirm('确定要删除这条积分记录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await pointsRecordApi.delete(row.id)
    ElMessage.success('删除成功')
    loadData()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitting.value = true
    
    if (isEdit.value) {
      await pointsRecordApi.update(form.id!, form)
      ElMessage.success('更新成功')
    } else {
      await pointsRecordApi.create(form)
      ElMessage.success('创建成功')
    }
    
    createDialogVisible.value = false
    loadData()
  } catch (error) {
    ElMessage.error(isEdit.value ? '更新失败' : '创建失败')
  } finally {
    submitting.value = false
  }
}

const resetForm = () => {
  Object.assign(form, {
    departmentId: '',
    responsiblePersonId: '',
    eventDescription: '',
    pointsType: 'add',
    pointsValue: 1,
    attachments: [],
    location: '',
    severity: 'low'
  })
  formRef.value?.clearValidate()
}

const handleDepartmentChange = async (departmentId: string) => {
  if (departmentId) {
    // 加载部门用户
    // departmentUsers.value = await getUserByDepartment(departmentId)
  }
  form.responsiblePersonId = ''
}

const showBatchImportDialog = () => {
  batchImportDialogVisible.value = true
  Object.assign(importForm, {
    file: null,
    departmentId: ''
  })
}

const handleFileChange = (file: any) => {
  importForm.file = file.raw
}

const handleBatchImport = async () => {
  if (!importForm.file) {
    ElMessage.warning('请选择要导入的文件')
    return
  }
  
  importing.value = true
  try {
    const result = await pointsRecordApi.batchImport({
      file: importForm.file,
      departmentId: importForm.departmentId
    })
    
    ElMessage.success(`导入完成！成功：${result.successCount}条，失败：${result.failCount}条`)
    batchImportDialogVisible.value = false
    loadData()
  } catch (error) {
    ElMessage.error('导入失败')
  } finally {
    importing.value = false
  }
}

const downloadTemplate = async () => {
  try {
    const response = await pointsRecordApi.downloadTemplate()
    const blob = new Blob([response], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = '积分记录导入模板.xlsx'
    link.click()
    window.URL.revokeObjectURL(url)
  } catch (error) {
    ElMessage.error('下载模板失败')
  }
}

const beforeUpload = (file: File) => {
  const isImage = file.type.startsWith('image/')
  const isExcel = file.type.includes('sheet') || file.name.endsWith('.xlsx') || file.name.endsWith('.xls')
  
  if (!isImage && !isExcel) {
    ElMessage.error('只能上传图片或Excel文件!')
    return false
  }
  
  const isLt10M = file.size / 1024 / 1024 < 10
  if (!isLt10M) {
    ElMessage.error('文件大小不能超过 10MB!')
    return false
  }
  
  return true
}

const handlePreview = (file: any) => {
  // 预览文件
}

const handleRemove = (file: any) => {
  // 移除文件
}

// 工具方法
const getStatusType = (status: string) => {
  const statusMap = {
    pending: 'warning',
    approved: 'success',
    rejected: 'danger',
    cancelled: 'info'
  }
  return statusMap[status] || 'info'
}

const getStatusText = (status: string) => {
  const statusMap = {
    pending: '待审批',
    approved: '已通过',
    rejected: '已拒绝',
    cancelled: '已取消'
  }
  return statusMap[status] || status
}

const getSeverityType = (severity: string) => {
  const severityMap = {
    low: 'success',
    medium: 'warning',
    high: 'danger'
  }
  return severityMap[severity] || 'info'
}

const getSeverityText = (severity: string) => {
  const severityMap = {
    low: '低',
    medium: '中',
    high: '高'
  }
  return severityMap[severity] || severity
}

const isImage = (url: string) => {
  return /\.(jpg|jpeg|png|gif|bmp|webp)$/i.test(url)
}

const getFileName = (url: string) => {
  return url.split('/').pop() || url
}

// 生命周期
onMounted(() => {
  loadData()
  // 加载部门列表
  // loadDepartments()
})
</script>

<style lang="scss" scoped>
.points-record {
  padding: 20px;
  
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    h2 {
      margin: 0;
      color: #303133;
    }
    
    .header-actions {
      display: flex;
      gap: 12px;
    }
  }
  
  .search-form {
    background: #fff;
    padding: 20px;
    border-radius: 8px;
    margin-bottom: 20px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  }
  
  .table-container {
    background: #fff;
    border-radius: 8px;
    padding: 20px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    
    .pagination-container {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }
  
  .text-success {
    color: #67c23a;
    font-weight: bold;
  }
  
  .text-danger {
    color: #f56c6c;
    font-weight: bold;
  }
  
  .record-detail {
    .event-description {
      margin: 20px 0;
      
      h4 {
        margin-bottom: 10px;
        color: #303133;
      }
      
      p {
        line-height: 1.6;
        color: #606266;
      }
    }
    
    .attachments {
      margin-top: 20px;
      
      h4 {
        margin-bottom: 10px;
        color: #303133;
      }
      
      .attachment-list {
        display: flex;
        flex-wrap: wrap;
        gap: 10px;
        
        .attachment-item {
          .file-item {
            display: flex;
            align-items: center;
            gap: 8px;
            padding: 8px 12px;
            border: 1px solid #dcdfe6;
            border-radius: 4px;
            background: #f5f7fa;
          }
        }
      }
    }
  }
}
</style>
